package handler

import (
	"log"
	"net/http"

	"github.com/google/uuid"
	"github.com/gorilla/websocket"
)

type websocketHandler struct {
}

func NewWebsocketHandler() *websocketHandler {
	return &websocketHandler{}
}

// upgrader 将 http 连接升级为 websocket连接
var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func (h *websocketHandler) HandlerConnections(w http.ResponseWriter, r *http.Request) {
	// 将http 连接升级为 websocket 连接
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {

		log.Fatal(err)
	}
	defer ws.Close()

	// 为连接生成一个唯一ID
	connID := uuid.New().String()

	log.Printf("[%s] 新的客户端连接建立，来源: %s", connID, r.RemoteAddr)
	defer log.Printf("[%s] 客户端连接断开，来源 %s", connID, r.RemoteAddr)

	for {
		// 读取客户端消息
		messageType, p, err := ws.ReadMessage()
		if err != nil {
			log.Printf("[%s] 读取消息错误: %v", connID, err)
			break
		}

		log.Printf("[%s] 收到消息: %v", connID, string(p))

		err = ws.WriteMessage(messageType, p)
		if err != nil {
			log.Printf("[%s] 发送消息错误: %v :", connID, err)
			break
		}
	}

}
